package com.keyware.kd.listener;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroSessionListener implements SessionListener{
	@Autowired 
	HttpServletRequest request;
	
	private static Logger log = Logger.getLogger(ShiroSessionListener.class);
	
	
	//会话过期
	@Override
	public void onExpiration(Session session) {
	    String sessionId = (String) session.getId();
        String loginIp = null;
        try {
        	loginIp = request.getRemoteAddr();
		} catch (Exception e) {
			log.error("request异常,获取失效人员IP错误。");
		}
        if(SessionCounter.activeSessions>0){
            if(SessionCounter.list.size() > 0){
            	if(loginIp == null){
            		String ip = SessionCounter.sessionIpMap.get(sessionId);
            		loginIp = ip;
                	Iterator<Entry<String, String>> iterator = SessionCounter.sessionIpMap.entrySet().iterator();
                	while(iterator.hasNext()){
                		Entry<String, String> next = iterator.next();
                		if(next.getValue().equals(ip)){
                			iterator.remove();
                		}
                	}
            	}
            	
                for(int i = 0;i < SessionCounter.list.size(); i ++){
                    if(SessionCounter.list.get(i).equals(loginIp)){
                    	SessionCounter.list.remove(i);
                        i--;
                    }
                }
            }
            SessionCounter.sessionIpMap.remove(sessionId);
            SessionCounter.activeSessions--;                   //在用户销毁的时候,从队列中踢出这个IP
            log.info("销毁SESSION,sessionId = " + sessionId
                             + "; loginIp = " + loginIp +"; 当前总SESSION值为 "+SessionCounter.activeSessions);
            if(SessionCounter.activeSessions == 0){
            	SessionCounter.list.removeAll(SessionCounter.list);
            	SessionCounter.sessionIpMap = new HashMap<String,String>();
            }
        }
	}

	//会话创建
	@Override
	public void onStart(Session arg0) {
		System.out.println("创建session");
	}

	//会话退出
	@Override
	public void onStop(Session arg0) {
		System.out.println("退出session");
	}

}
